package client

import (
	"gitee.com/jnshao/go-start/projects/crawler/engine"
	"log"

	"gitee.com/jnshao/go-start/projects/crawler_distributed/config"
	"gitee.com/jnshao/go-start/projects/crawler_distributed/rpcsupport"
)

func ItemSaver(address string) (c chan engine.Item, err error) {
	itemChan := make(chan engine.Item)

	client, err := rpcsupport.NewClient(address)
	if err != nil {
		return nil, err
	}
	go func() {
		itemCount := 0
		for {
			item := <-itemChan
			itemCount++
			log.Printf("Save #%vitem: %+v", itemCount, item)

			var result string
			err = client.Call(config.ItemSaverRpc, item, &result)

			if err != nil || result != "ok" {
				log.Printf("Save error #%vitem: %+v", itemCount, item)
				continue
			}
		}
	}()
	return itemChan, nil
}
